﻿using Max.PH6_2006A.LowCode.Domain;
using Max.PH6_2006A.LowCode.IService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.PH6_2006A.LowCode.API.Controllers
{

    /// <summary>
    /// 菜单接口
    /// </summary>
    [Route("rbac/menu")]
    [ApiController]
    public class SystemMenuController : BaseCRUDController<SystemMenu, SystemMenu, SystemMenu>
    {
        ISystemMenuService _service;
        public SystemMenuController(ISystemMenuService service) : base(service)
        {
            _service = service;
        }

        /*
         * 
         * 
         * **/

        
        /// <summary>
        /// 递归菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet("recursion")]
        [AllowAnonymous]
        public IActionResult RecursionMenu()
        {
            DTO.ApiResultReturnDto dto = new();
            try
            {
                var data = _service.Query("select * from systemmenu").ToList();
                var result = this.RecursionMenu(data);
                dto.Data = result;
            }
            catch (Exception ex)
            {
                dto.Code = DTO.ApiResultReturnCode.Failed;
                dto.Message = ex.Message;

            }
            return Ok(dto);
        }

        private List<dynamic> RecursionMenu(List<SystemMenu> data, Guid? id=null) 
        {
            var list =  data.Where(x => x.FatherId == id).ToList();

            List<dynamic> result = new();

            //循环
            list.ForEach(x => {
                var let = this.RecursionMenu(data, x.Id);
                dynamic d = new {
                    x.Id,
                    x.Name,
                    x.Url,
                    children = (let == null || let.Count <= 0) ? null : let
                };
                result.Add(d);
            });

            return result;
        }
    }
}
